/**
 * @fileoverview This should be prefixed to instrumented JS files that will
 * be served by the Firefox extension.
 * @author bolinfest@gmail.com (Michael Bolin)
 */
(function() {
  // goog.provide('jsbloat');
  var jsbloat = jsbloat || {};
  
  jsbloat.isIframeLoaded = false;

  // http://softwareas.com/whats-the-maximum-z-index
  jsbloat.MAX_ZINDEX = 2147483647;
  
  jsbloat.iframe;
  
  jsbloat.initializeIframe = function(input) {
    // This function is idempotent.
    if (jsbloat.iframe) return;

    // Export global functions.
    var doc = input.ownerDocument;
    var win = doc.defaultView;
    if (!win['__JSBLOAT__']) {
      var library = win['__JSBLOAT__'] = {};
      library['getJsCoverageHtml'] = function() {
        return JS_COVERAGE_HTML;
      };
      library['notifyLoaded'] = function() {
        jsbloat.isIframeLoaded = true;

        // Now that the frame is finished loading, kick off the jsbloat-specific
        // initialization routine.
        jsbloat.iframe.contentWindow.jscoverage_jsbloat_init();
      };
      library['hide'] = function() {
        jsbloat.iframe.style.display = 'none';
      }
    }
    
    var iframe = jsbloat.iframe = doc.createElement('iframe');
    iframe.src = 'javascript:parent.__JSBLOAT__.getJsCoverageHtml()';
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.style.position = 'absolute';
    iframe.style.top = '0';
    iframe.style.left = '0';
    iframe.style.zIndex = jsbloat.MAX_ZINDEX;
    iframe.style.backgroundColor = 'white';
    iframe.style.display = 'none';
    doc.body.appendChild(iframe);
  };

  jsbloat.tryUpdateSummary = function() {
    if (jsbloat.isIframeLoaded) {
      jsbloat.iframe.contentWindow.jscoverage_recalculateSummaryTab();
    }
  };
  
  jsbloat.show = function(e) {
    var input = /** @type {Element} */ (e.target);
    jsbloat.initializeIframe(input);

    var iframe = jsbloat.iframe;
    if (iframe.style.display == 'none') {
      // Try to update the Summary tab before displaying the iframe.
      jsbloat.tryUpdateSummary();

      iframe.style.display = '';
    }
  };

  jsbloat.onWindowLoad = function() {
    var doc = document;
    var input = doc.createElement('input');
    input.type = 'button';
    input.value = 'Show JSCoverage results';
    input.style.position = 'absolute';
    input.style.top = '0';
    input.style.left = '0';
    input.style.zIndex = jsbloat.MAX_ZINDEX;
    input.addEventListener('click', jsbloat.show, false);
    document.body.appendChild(input);
  };

  jsbloat.init = function() {
    if (document.readyState == 'complete') {
      jsbloat.onWindowLoad();
    } else {
      window.addEventListener('load', jsbloat.onWindowLoad, false);
    }
  };
  
  jsbloat.init();
})();
